let unlock = require("./unLock.js");
importClass(org.json.JSONObject)
timer = {}

let oneMinute = 30 * 1000

timer.timeExecute = function(config) {
  console.log("定时时间：" + config.exeTime.getTime())
  console.log("当前时间：" + Date.now())
  // 当前时间大于执行时间，如果重复则下一次时间执行，否则不执行
  if(Date.now() > config.exeTime.getTime()) {
    nextExecute(config)
    return
  } 
  // 距离定时时间2分钟前setTimeOut
  let sleepTime = config.exeTime.getTime() - Date.now() - oneMinute
  if(sleepTime <= 0) {
    console.log("小于两分钟：轮询执行")
    runExecute(config);
  } else {
    console.log("大于两分钟：定时执行")
    setTimeout(runExecute, sleepTime, config)
  }
  
}

timer.getDate = function(strDate) {
  var st = strDate;
  var a = st.split(" ")
  var b = a[0].split("-")
  var c = a[1].split(":")
  var date = new Date(b[0], b[1] - 1, b[2], c[0], c[1], c[2])
  return date
}

function runExecute(config) {
  console.log("prepre time" + Date.now().toLocaleString())
  unlock.exec(config.password)
  config.prepare()
  let now = getDamaiTimestamp() - 70

  while(now < config.exeTime){
    console.log("run time" + now)
    sleep(70)
    now = getDamaiTimestamp() - 70
  } 
  console.log("execute time start ：" + now)
  //device.wakeUpIfNeeded() 
  config.execution()
  console.log("execute time end：" + now)
  nextExecute(config)
}

function nextExecute(config) {
  if(config.isRepeat) {
    console.log("下次时间：" + Date.now().toLocaleString())
    config.exeTime = getNextDate(config.exeTime)
    timer.timeExecute(config)
  } else {
    console.log("定时任务结束")
  }
}

function getNextDate(dateTime) {
  dateTime = dateTime.setSeconds(dateTime.getSeconds() + 60)
  //dateTime = dateTime.setDate(dateTime.getDate() + 40)
  return new Date(dateTime)
}

/**
 * 
 * @returns 大麦服务器时间戳
 */
function getDamaiTimestamp() {
  try{
    let time = new JSONObject(http.get("https://mtop.damai.cn/gw/mtop.common.getTimestamp/", {
      headers: {
          'Host': 'mtop.damai.cn',
          'Content-Type': 'application/json;charset=utf-8',
          'Accept': '*/*',
          'User-Agent': 'floattime/1.1.1 (iPhone; iOS 15.6; Scale/3.00)',
          'Accept-Language': 'zh-Hans-CN;q=1, en-CN;q=0.9',
          'Accept-Encoding': 'gzip, deflate, br',
          'Connection': 'keep-alive'
      }
    }).body.string()).getJSONObject("data").getString("t");
    console.log("taobaotime：" + time)
    return time
  } catch(e) {
    console.log(e.getMessage())
    return Date.now().getTime() - 1800;
  }
}


module.exports = timer